<script setup lang="ts">
import dayjs from 'dayjs'
import ShiftConfig from './ShiftConfig.vue'

import { useSettings } from './MixinSettings'
import { usePlans } from './MixinPlans'
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'
import type { ScheduleScheme } from '@/types'

import { schedulingApi } from '@/api'

const props = defineProps<{
  data: Pick<
    ScheduleScheme,
    'id' | 'name' | 'shiftUnit' | 'shift' | 'team'
  >
}>()
const emits = defineEmits<{
  (e: 'save-success'): void
}>()

const dialogRef = ref<InstanceType<typeof CustomDialog>>()

const scheduleScemeName = computed(() => {
  return props.data.name
})

const shiftCount = computed(() => {
  return props.data.shift.length
})
const teams = computed(() => {
  return props.data.team
})
// 自动填充“轮休”的班次
const shifts = computed(() => {
  const n: number
    = teams.value.length - props.data.shift.length
  const now = Date.now()
  return [
    ...props.data.shift,
    ...Array.from({ length: n }, (_, i) => {
      return {
        id: now + i,
        name: '轮休',
        time: '',
        duration: '',
        isCrossDay: 0,
      }
    }),
  ] as ScheduleScheme['shift']
})

const year = ref(new Date())
const planDateStrings = computed(() => {
  const n = teams.value.length
  const date = dayjs(year.value).startOf('year')
  return Array.from({ length: n }, (_, i) => {
    return date.add(i, 'day').format('YYYY-MM-DD')
  })
})

const { settingIds, setIds, settingTeams }
  = useSettings(teams)
const teamsConfig = computed(() => {
  return unref(settingIds).map(
    v => unref(teams).find(vv => vv.id === v)!,
  )
})
const { plans } = usePlans(
  teamsConfig,
  planDateStrings,
  shiftCount,
)

function clearSelectSettingId(index: number) {
  const copyIds = [...unref(settingIds)]
  // @ts-expect-error undefined assign to number
  copyIds.splice(index, 1, undefined)
  setIds(copyIds)
}

async function clickSave(done: () => void) {
  const checkedIds = unref(settingIds).filter(
    v => v !== undefined,
  )
  if (checkedIds.length !== unref(teams).length) {
    done()
    ElMessage.error('请完成选择班组与班次的配置')
  }
  else {
    function startTime(time: string) {
      return time
        ? time.replace(/\s/g, '').split('-')[0]
        : ''
    }
    function endTime(time: string) {
      return time
        ? time.replace(/\s/g, '').split('-')[1]
        : ''
    }
    function teamName(index: number) {
      const t = unref(teams)[index]
      return t?.name
    }
    const params = {
      year: `${unref(year).getFullYear()}`,
      schedulingSchemeName: unref(scheduleScemeName),
      schedulingPlanList: unref(shifts).map((v, i) => ({
        shiftName: v.name,
        teamName: teamName(i) || '',
        startTime: startTime(v.time),
        endTime: endTime(v.time),
        totalTimeMinute: v.duration,
        overnightShift: v.isCrossDay,
      })),
    }
    // console.log('params: ', params);
    try {
      await schedulingApi.saveSchedulingPlan(
        params as schedulingApi.ScheuldingSaveSchedulingPlanParams,
      )
      done()
      close()
      ElMessage.success('创建计划成功')
      emits('save-success')
    }
    catch (e) {
      done()
    }
  }
}

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="生成排班计划"
    class="plan-modal"
    confirm-button-text="创建计划"
    need-saving
    fullable
    @confirm="clickSave"
  >
    <div
      class="width-fill height-fill content-wrapper flex"
    >
      <div
        class="flex-fillRemaining flex-direction plan-wrapper flex"
      >
        <ElDescriptions border :column="1">
          <ElDescriptionsItem label="排班方案" :width="70">
            {{ scheduleScemeName }}
          </ElDescriptionsItem>
          <ElDescriptionsItem
            label="排班计划时间"
            :width="70"
          >
            <ElDatePicker v-model="year" type="year" />
          </ElDescriptionsItem>
        </ElDescriptions>
        <div
          class="margin-top-sm flex-fillRemaining border-radius-base plan-and-setting flex border"
        >
          <div
            class="height-fill flex-direction settings basis-df flex"
          >
            <p
              class="padding-sm margin-top-0"
              style="font-size: 16px"
            >
              班次与班组配置
            </p>
            <ShiftConfig
              :shifts="shifts"
              style="padding-top: 0; padding-bottom: 0"
            >
              <template #team="{ index }">
                <ElSelect
                  v-model="settingIds[index]"
                  clearable
                  @clear="clearSelectSettingId(index)"
                >
                  <ElOption
                    v-for="(team, i) in settingTeams[index]"
                    :key="i"
                    :label="team.name"
                    :value="team.id"
                    :disabled="team.disabled"
                  />
                </ElSelect>
              </template>
            </ShiftConfig>
          </div>
          <ElDivider
            direction="vertical"
            class="!height-fill"
          />
          <div
            class="basis-df height-fill flex-direction plans flex"
          >
            <p
              class="padding-sm margin-top-0"
              style="font-size: 16px"
            >
              最近一轮排班计划
              <small style="color: var(--el-color-danger)">
                （注：根据班次与班组配置顺序循环推导）
              </small>
            </p>
            <div class="padding-sm timeline-wrapper">
              <ElTimeline>
                <ElTimelineItem
                  v-for="plan in plans"
                  :key="plan.date"
                  :timestamp="plan.date"
                  placement="top"
                >
                  <ElCard shadow="never" class="card">
                    <ShiftConfig :shifts="shifts">
                      <template #team="{ index }">
                        <p>{{ plan.teams[index]?.name }}</p>
                      </template>
                    </ShiftConfig>
                  </ElCard>
                </ElTimelineItem>
              </ElTimeline>
            </div>
          </div>
        </div>
      </div>
    </div>
  </CustomDialog>
</template>

<style>
.plan-modal {
  min-width: 960px !important;
}
.plan-modal.is-fullscreen .content-wrapper {
  height: 100%;
}
</style>

<style lang="scss" scoped>
.content-wrapper {
  height: 50vh;
}
.plans,
.settings,
.plan-and-setting,
.timeline-wrapper,
.content-wrapper {
  @include roll($snapType: proximity);
}
.plans,
.settings {
  color: var(--el-text-color-regular);
}
.card {
  --el-card-padding: 0;
}
.timeline-wrapper :deep(.el-timeline) {
  padding: 0;
}
</style>
